﻿namespace ScrumLite.Services
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Transactions;
    using System.Linq;
    using Contracts;

    public class LinqRolesService : IRolesService
    {
        ScrumLite.Data.IRoleStore store;

        public LinqRolesService(ScrumLite.Data.IRoleStore store)
        {
            this.store = store;
        }

        public LinqRolesService()
            : this(new ScrumLite.Data.RoleStore())
        {
        }

        public ProjectRole GetProjectRole(string roleId)
        {
            ScrumLite.Data.Role role = store.GetRole(new Guid(roleId));

            ProjectRole projectRole = new ProjectRole { Id = role.id, Name = role.name };

            return projectRole;
        }

        public Collection<ProjectRole> GetProjectRoles(string projectId)
        {
            ScrumLite.Data.Role[] roles =  store.GetProjectRoles(new Guid(projectId));

            List<ProjectRole> projectRoles = new List<ProjectRole>();

            foreach (ScrumLite.Data.Role role in roles)
            {
                projectRoles.Add(new ProjectRole { Id = role.id, Name = role.name });
            }

            return new Collection<ProjectRole>(projectRoles);
        }

        public Collection<Ability> GetAbilities(string projectId, string roleId)
        {
            ScrumLite.Data.Ability[] abilities = store.GetRoleAbilities(new Guid(projectId), new Guid(roleId));

            List<Ability> roleAbilities = new List<Ability>();

            foreach (ScrumLite.Data.Ability ability in abilities)
            {
                roleAbilities.Add(new Ability { Id = ability.id, Name = ability.name });
            }

            return new Collection<Ability>(roleAbilities);
        }

        public void AddRoleToProject(string projectId, string roleName, string[] abilityIds)
        {
            using (TransactionScope scope = new TransactionScope())
            {
                this.store.AddRoleToProject(new Guid(projectId), roleName, abilityIds);
                scope.Complete();
            }
        }
    }
}
